package com.wgcloud.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Slf4j
@Aspect
@Component
public class CustomLogAspect {

    private static final Logger logger = LoggerFactory.getLogger(CustomLogAspect.class);

    // 定义切点，匹配所有带有CustomLog注解的方法
    @Pointcut("@annotation(com.wgcloud.aop.CustomLog)")
    public void customLogPointcut() {
    }

    // 在方法执行前执行
//    @Before("customLogPointcut()")
//    public void beforeMethodExecution(JoinPoint joinPoint) {
//        String methodName = joinPoint.getSignature().getName();
//        log.info("Executing method: {} before", methodName);
//    }

    // 在方法执行后执行（无论是否抛出异常）
//    @AfterReturning(pointcut = "customLogPointcut()", returning = "result")
//    public void afterMethodExecution(JoinPoint joinPoint, Object result) {
//        String methodName = joinPoint.getSignature().getName();
//        log.info("Executing method: {} after, result: {}", methodName, result);
//    }

    // 使用@Around注解来记录方法的执行时间
    @Around("customLogPointcut()")
    public Object aroundMethodExecution(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        String methodName = joinPoint.getSignature().getName();
        try {
            // 执行目标方法
            return joinPoint.proceed();
        } finally {
            long endTime = System.currentTimeMillis();
            long executionTime = endTime - startTime;
            log.info("执行方法: {} 本次耗时为: {} ms", methodName, executionTime);
        }
    }
}